package com.dy.yunying.biz.service.manage.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dy.yunying.api.constant.ChannelConstants;
import com.dy.yunying.api.dto.ChannelManageDto;
import com.dy.yunying.api.entity.ChannelManageDO;
import com.dy.yunying.api.req.ChannelManageReq;
import com.dy.yunying.api.vo.ChannelManageVo;
import com.dy.yunying.biz.config.YunYingProperties;
import com.dy.yunying.biz.dao.manage.ext.ChannelManageDOMapperExt;
import com.dy.yunying.biz.service.manage.ChannelManageService;
import com.pig4cloud.pig.admin.api.entity.SysUser;
import com.pig4cloud.pig.admin.api.feign.RemoteUserService;
import com.pig4cloud.pig.common.core.constant.CommonConstants;
import com.pig4cloud.pig.common.core.constant.SecurityConstants;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import jodd.introspector.MapperFunction;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Collectors;

@Transactional
@Service
@Slf4j
public class ChannelManageServiceImpl extends ServiceImpl<ChannelManageDOMapperExt, ChannelManageDO> implements ChannelManageService {

	@Autowired
	private ChannelManageDOMapperExt promotionChannelDOMapperExt;


	@Autowired
	private RemoteUserService remoteUserService;

	@Autowired
	private YunYingProperties yunYingProperties;


	/**
	 * 添加主渠道
	 *
	 * @param channel
	 * @return
	 */
	@Override
	public R<Integer> saveParentchl(ChannelManageDto channel) {
		//根据主渠道编码或者主渠道名称  查询数据库是否已经存在
		int count = promotionChannelDOMapperExt.insertchl(channel);
		channel.setChncode(channel.getId().toString());
		promotionChannelDOMapperExt.updateByPrimaryKey(channel);
		if (count > 0) {
			return R.ok(1, "添加主渠道成功");
		}
		return R.failed(0, "添加主渠道失败");
	}

	/*
	 *  添加主渠道时  默认生成子渠道
	 */
	@Override
	public void savedefaultchl(ChannelManageDto channel) {
		// 添加主渠道时默认添加子渠道
		channel.setPid(Integer.valueOf(channel.getChncode()));
		channel.setParentCode(channel.getChncode());
		channel.setId(null);
		// 子渠道默认生成
		channel.setIsDefault(1);
		// 子渠道 名称 默认生成
		channel.setChnname(channel.getChnname() + "默认");
		// 默认子渠道编码
		channel.setChncode(channel.getChncode() + ChannelConstants.CHANNEL_PACK_SEP);
		channel.setRtype(2);
		channel.setPaytype(1);
		channel.setIsup(1);
		// 添加默认 生成子渠道
		int countchl = promotionChannelDOMapperExt.insertchl(channel);
		// 默认生成子渠道编码
		channel.setChncode(channel.getChncode() + channel.getId());
		promotionChannelDOMapperExt.updateByPrimaryKey(channel);
	}


	/**
	 * 查询主渠道列表
	 *
	 * @param req
	 * @return
	 */
	@Override
	public IPage<ChannelManageVo> queryParentchlList(ChannelManageReq req) {
		Page pge = new Page();
		pge.setSize(req.getSize());
		pge.setCurrent(req.getCurrent());
		IPage<ChannelManageVo> page = promotionChannelDOMapperExt.queryParentchlList(req);
		List<ChannelManageVo> list = page.getRecords();
		Map<String, String> platFormMap = this.platFormMap();
		if (CollectionUtils.isNotEmpty(list)) {
			//过滤cps主渠道
			List<ChannelManageVo> collect = list.stream().filter(channelManageVo -> !yunYingProperties.getCpsParentChannelId().equals(channelManageVo.getId())).map((MapperFunction<ChannelManageVo, ChannelManageVo>) channelManageVo -> {
				ChannelManageVo target = new ChannelManageVo();
				BeanUtils.copyProperties(channelManageVo, target);
				if (Objects.nonNull(target.getPlatform())) {
					target.setPlatformname(platFormMap.get(String.valueOf(target.getPlatform())));
				}
				return target;
			}).collect(Collectors.toList());
			page.setRecords(collect);
		}
		return page;
	}

	/**
	 * 更新主渠道 编码或者主渠道名称
	 *
	 * @param
	 * @return
	 */
	@Override
	public ChannelManageVo getVOByPK(Integer id) {
		return promotionChannelDOMapperExt.getVOByPK(id);
	}

	@Override
	public ChannelManageVo getVOByCode(String code) {
		return promotionChannelDOMapperExt.getVOByCode(code);
	}


	/**
	 * 更新主渠道
	 *
	 * @param channel
	 * @return
	 */
	@Override
	public R updateParentchl(ChannelManageDto channel) {
		// 主渠道名称和主渠道编码数据库中已经有
		channel.setUpdatetime(new Date());
		int count = promotionChannelDOMapperExt.updateByPrimaryKeySelective(channel);
		if (count > 0) {
			return R.ok("更新主渠道成功");
		}
		return R.failed("更新主渠道失败");
	}

	/**
	 * 编辑子渠道
	 */
	@Override
	public R updateChl(ChannelManageDto channel) {
		String parentChl = channel.getChncode();
		channel.setChnname(channel.getSonname());
		channel.setId(channel.getChlId());
		channel.setUpdatetime(new Date());
		// 子渠道编码
		channel.setChncode(parentChl + ChannelConstants.CHANNEL_PACK_SEP + channel.getChlId());
		int count = promotionChannelDOMapperExt.updateByPrimaryKeySelective(channel);
		if (count > 0) {
			return R.ok("更新子渠道成功");
		}
		return R.failed("更新子渠道失败");
	}

	/**
	 * 添加子渠道
	 *
	 * @param channel
	 * @return
	 */
	@Override
	public R savechl(ChannelManageDto channel) {
		channel.setCreator(Long.valueOf(SecurityUtils.getUser().getId()));
		channel.setEditor(Long.valueOf(SecurityUtils.getUser().getId()));
		//负责人
		channel.setIsdelete(0);
		channel.setUpdatetime(new Date());
		channel.setCreatetime(new Date());
		channel.setRtype(2);
		int count = promotionChannelDOMapperExt.insertchl(channel);
		if (count > 0) {
			channel.setChncode(channel.getParentCode() + ChannelConstants.CHANNEL_PACK_SEP + channel.getId().toString());
			channel.setParentCode(channel.getParentCode());
			promotionChannelDOMapperExt.updateByPrimaryKey(channel);
			return R.ok(channel, "添加子渠道成功");
		}
		return R.failed("添加子渠道失败");
	}


	/**
	 * 根据子渠道编码 获取 渠道信息
	 *
	 * @param chncode
	 * @return
	 */
	/**
	 *
	 */
	@Deprecated
	public ChannelManageVo selectChildChlByCode(String chncode) {
		ChannelManageDto channel = new ChannelManageDto();
		channel.setChncode(chncode);
		List<ChannelManageVo> channelManageVo = promotionChannelDOMapperExt.queryChlByCodeOrName(channel);
		if (channelManageVo.size() > 0) {
			return channelManageVo.get(0);
		} else {
			return null;
		}
	}

	@Deprecated
	public ChannelManageVo selectChildChlByCodeIgnoreDel(String chncode) {
		ChannelManageDto channel = new ChannelManageDto();
		channel.setChncode(chncode);
		List<ChannelManageVo> channelManageVo = promotionChannelDOMapperExt.queryChlByCodeOrNameIgnoreDel(channel);
		if (channelManageVo.size() > 0) {
			return channelManageVo.get(0);
		} else {
			return null;
		}
	}

	@Override
	public ChannelManageVo selectParentChlByCode(String chncode) {
		return promotionChannelDOMapperExt.selectParentChlByCode(chncode);
	}

	@Override
	public ChannelManageVo selectParentChlByCodeIgnoreDel(String chncode) {
		return promotionChannelDOMapperExt.selectParentChlByCodeIgnoreDel(chncode);
	}


	/**
	 * 查询子渠道列表
	 *
	 * @param req
	 * @return
	 */
	@Override
	public IPage<ChannelManageVo> queryChlList(ChannelManageReq req) {
		Page pge = new Page();
		pge.setSize(req.getSize());
		pge.setCurrent(req.getCurrent());
		IPage<ChannelManageVo> page = promotionChannelDOMapperExt.queryAdminChlList(req);

		if (page.getRecords() != null || page.getRecords().size() > 0) {

			R<List<SysUser>> r = remoteUserService.getUserList(SecurityConstants.FROM_IN);

			Map<String, String> map = new HashMap<>();
			if (r.getCode() == CommonConstants.SUCCESS) {
				List<SysUser> list = r.getData();
				map = list.stream().collect(Collectors.toMap(
						o -> {
							return String.valueOf(o.getUserId());
						}, SysUser::getRealName));
			}

			Map<String, String> finalMap = map;
			page.getRecords().forEach(data -> {
				Long manage = data.getManage();
				if (manage != null) {
					String creator = String.valueOf(manage);
					data.setLeadperson(finalMap.get(creator) == null ? creator : finalMap.get(creator));
				} else {
					data.setLeadperson("-");
				}
			});
		}

		return page;
	}

	/**
	 * 查询平台类型
	 *
	 * @param map
	 * @return
	 */
	@Override
	public List<Map<String, String>> queryPlatForm(Map<String, Object> map) {
		return promotionChannelDOMapperExt.queryPlatForm(map);
	}


	/**
	 * 负责id 查到对应负责人
	 *
	 * @return user_id, real_name
	 */
	public Map<String, String> platFormMap() {
		//投放人名称
		Map<String, Object> map = new HashMap<>();
		List<Map<String, String>> platFormlist = promotionChannelDOMapperExt.queryPlatForm(map);
		Map<String, String> platFormMap = new HashMap<>();
		platFormlist.forEach(manageData -> {
			platFormMap.put(manageData.get("code"), manageData.get("dictValue"));
		});
		return platFormMap;
	}

	/**
	 * 通过投放人  查询对应投放人下的子渠道
	 *
	 * @param map
	 * @return
	 */
	@Override
	public List<Map<String, Object>> queryChannelFromManager(Map<String, Object> map) {
		return promotionChannelDOMapperExt.queryChannelFromManager(map);
	}

	/**
	 * 获取主渠道的默认子渠道
	 *
	 * @param pid
	 * @return
	 */
	@Override
	public ChannelManageVo getDefaultSonVO(int pid) {
		return promotionChannelDOMapperExt.getDefaultSonVO(pid);
	}


	@Override
	public R saveCpsChl(ChannelManageDto channel) {
		channel.setCreator(Long.valueOf(SecurityUtils.getUser().getId()));
		channel.setEditor(Long.valueOf(SecurityUtils.getUser().getId()));
		//负责人
		channel.setIsdelete(0);
		channel.setUpdatetime(new Date());
		channel.setCreatetime(new Date());
		channel.setRtype(2);
		int count = baseMapper.insert(channel);
		if (count > 0) {
			channel.setChncode(channel.getParentCode() + ChannelConstants.CHANNEL_PACK_SEP + channel.getId().toString());
			channel.setParentCode(channel.getParentCode());
			promotionChannelDOMapperExt.updateByPrimaryKey(channel);
			return R.ok(channel, "添加子渠道成功");
		}
		return R.failed("添加子渠道失败");
	}
}